﻿Imports System.IO
Imports System.ComponentModel
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Windows.Forms

Partial Public Class WindowGameEditor
    Implements INotifyPropertyChanged

#Region "Members"

    Private m_GameInfo As GameInfo

    Private WithEvents m_UpdatesTimer As Timers.Timer

    Private m_GridLines As Integer

    Private WithEvents m_AddMediaDialog As AddMediaDialog

    Private WithEvents m_adorLayer As AdornerLayer


    Private mouseLeftDownPoint As Point

    Private rubberBand As Shape

    Private m_ShownRectangles As New List(Of Rectangle)

    Private m_isSliderMovedByUser As Boolean = False

    Private m_idCounter As Integer = 2
#End Region

#Region "Constructors"

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        m_GameInfo = New GameInfo

        m_adorLayer = AdornerLayer.GetAdornerLayer(MediaElement1)


    End Sub
#End Region

#Region "MediaElement"
    Private Sub MediaElement1_MediaEnded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            MediaElement1.Stop()
        Catch ex As Exception

        End Try

    End Sub

    Private Sub MediaElement1_MediaOpened(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            timelineSlider.Maximum = MediaElement1.NaturalDuration.TimeSpan.TotalMilliseconds
        Catch ex As Exception
            timelineSlider.Maximum = New TimeSpan(0, 0, 1).TotalMilliseconds
        End Try

    End Sub

    Private Sub ButtonPlay_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            MediaElement1.Play()
        Catch ex As Exception
            MsgBox("Failed to play media: " & ex.ToString)
        End Try

    End Sub

    Private Sub ButtonPause_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            MediaElement1.Pause()
        Catch ex As Exception
            MsgBox("Failed to pause media: " & ex.ToString)
        End Try

    End Sub

    Private Sub ButtonStop_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            MediaElement1.Stop()
        Catch ex As Exception

        End Try

    End Sub

    Private Sub timelineSlider_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double))
        Try
            If m_isSliderMovedByUser Then
                Dim SliderValue As Integer = CInt(timelineSlider.Value)

                Dim ts As TimeSpan = New TimeSpan(0, 0, 0, 0, SliderValue)
                MediaElement1.Position = ts
            End If

        Catch ex As Exception
            MsgBox("Operation Failed : " & ex.ToString)
        End Try
    End Sub

    Private Sub timelineSlider_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        m_isSliderMovedByUser = True

    End Sub

    Private Sub timelineSlider_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        m_isSliderMovedByUser = False
    End Sub

    Private Sub timelineSlider_PreviewMouseDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        m_isSliderMovedByUser = True
    End Sub

    Private Sub timelineSlider_PreviewMouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        m_isSliderMovedByUser = False
    End Sub

    Public Delegate Sub ItsTimeDel()

    Private Sub ItsTimeSlider()
        Try
            If Not m_isSliderMovedByUser Then
                Dim l_curTimeSpan = MediaElement1.Position
                Dim l_timeSpan As New TimeSpan(l_curTimeSpan.Days, l_curTimeSpan.Hours, l_curTimeSpan.Minutes, l_curTimeSpan.Seconds, 0)

                timelineSlider.Value = l_timeSpan.TotalMilliseconds
            End If

        Catch ex As Exception
            MsgBox("Operation Failed : " & ex.ToString)
        End Try

    End Sub

    Private Sub ItsTimeLabel()
        Dim l_curTimeSpan = MediaElement1.Position

        Dim l_timeSpan As New TimeSpan(l_curTimeSpan.Days, l_curTimeSpan.Hours, l_curTimeSpan.Minutes, l_curTimeSpan.Seconds, 0)

        TextboxTime.Text = l_timeSpan.ToString

    End Sub
#End Region

#Region "Media Files List"
    Private Sub ButtonRemoveMedia_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

    End Sub

    Private Sub OnAddMovie(ByVal p_MediaFileType As MediaFileType, ByVal p_Url As String) Handles m_AddMediaDialog.OnOkButtonClick
        Dim l_fileName = System.IO.Path.GetFileName(p_Url)
        Dim l_Path = Path.Combine(GetTempFolderPath, l_fileName)
        'Dim l_Path = "C:\Users\Gal\Desktop\New Folder"
        If Not Directory.Exists(Path.GetDirectoryName(l_Path)) Then
            Directory.CreateDirectory(Path.GetDirectoryName(l_Path))
        End If

        Dim l_mediaFile As New MediaFile(0, p_Url, p_MediaFileType, l_Path)
        Dim l_thread As New System.Threading.Thread(AddressOf Me.DownloadSingleFile)
        l_thread.Start(l_mediaFile)


        'Dim l_Success = DownloadFile(p_Url, l_Path)
        'If l_Success Then
        '    Dim l_mediafile As MediaFile
        '    If p_MediaFileType = MediaFileType.Movie Then
        '        l_mediafile = New Movie(getIdCounter, p_Url, p_MediaFileType, l_Path)
        '    Else
        '        l_mediafile = New MediaFile(getIdCounter, p_Url, p_MediaFileType, l_Path)
        '    End If

        '    m_GameInfo.MediaFiles.Add(l_mediafile)
        '    ListViewMediaFiles.ItemsSource = New List(Of MediaFile)(m_GameInfo.MediaFiles)
        '    ListViewMediaFiles.SelectedItem = l_mediafile
        '    rubberBand = Nothing

        '    m_AddMediaDialog.Close()
        'Else
        '    MsgBox("Failed to add the media")
        'End If
    End Sub

    Private Sub OnDownloadFileCompleted(ByVal p_mediaFileType As MediaFileType, ByVal p_url As String, ByVal p_path As String, ByVal p_success As Boolean) Handles Me.DownloadCopleted
        If p_success Then
            Dim l_mediafile As MediaFile
            If p_mediaFileType = MediaFileType.Movie Then
                l_mediafile = New Movie(getIdCounter, p_url, p_mediaFileType, p_path)
            Else
                l_mediafile = New MediaFile(getIdCounter, p_url, p_mediaFileType, p_path)
            End If

            m_GameInfo.MediaFiles.Add(l_mediafile)
            ListViewMediaFiles.Dispatcher.Invoke(New ChangeMediaFilesItemsSourceDel(AddressOf ChangeMediaFilesItemsSource), m_GameInfo.MediaFiles, l_mediafile)
            
        Else
            MsgBox("Failed to add the media with URL: " & p_url)
        End If
    End Sub

    Private Delegate Sub ChangeMediaFilesItemsSourceDel(ByVal p_MediaFiles As List(Of MediaFile), ByVal p_SelectedFile As MediaFile)

    Private Sub ChangeMediaFilesItemsSource(ByVal p_MediaFiles As List(Of MediaFile), ByVal p_SelectedFile As MediaFile)
        Try
            ListViewMediaFiles.ItemsSource = New List(Of MediaFile)(p_MediaFiles)
            If p_SelectedFile IsNot Nothing Then
                ListViewMediaFiles.SelectedItem = p_SelectedFile
            ElseIf ListViewMediaFiles.Items.Count > 0 Then
                ListViewMediaFiles.SelectedItem = ListViewMediaFiles.Items(0)
            End If

            rubberBand = Nothing

            m_AddMediaDialog.Close()
        Catch ex As Exception

        End Try
        
    End Sub

    Private Sub DownloadSingleFile(ByVal p_mediaFile As MediaFile)

        Dim l_Success = DownloadFile(p_mediaFile.Url, p_mediaFile.Path)

        RaiseEvent DownloadCopleted(p_mediaFile.Type, p_mediaFile.Url, p_mediaFile.Path, l_Success)
    End Sub

    Private Sub ButtonAddMedia_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        m_AddMediaDialog = New AddMediaDialog
        m_AddMediaDialog.Owner = Me
        m_AddMediaDialog.ShowDialog()
    End Sub

    Private Sub ListViewMediaFiles_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
        Try
            rubberBand = Nothing
            Dim l_mediaFile As MediaFile = SelectedMediaFile
            canvas1.Children.Clear()
            showGlobalEventsErea()

            If l_mediaFile.Type = MediaFileType.Movie Then
                Dim l_movie As Movie = DirectCast(l_mediaFile, Movie)

                MediaElement1.Source = New Uri(l_movie.Path)
                MediaElement1.Play()

                m_UpdatesTimer = New Timers.Timer(100)
                m_UpdatesTimer.Enabled = True

                RBMovieClickEvents.IsEnabled = True
                RBMovieClickEvents.IsChecked = True

                'if it's a movie - select the correct radio button and navigate to the right events list (global/movies events)
                'if not movie - set the Movie events radio button to false - true eitherwise
                ListViewMovieEvents.ItemsSource = l_movie.Events
                RBEndMovieResults.IsChecked = True
                ListViewResults.ItemsSource = New List(Of Result)(l_movie.EndOfMovieResults)
                If ListViewResults.Items.Count > 0 Then
                    ListViewResults.SelectedItem = ListViewResults.Items(0)
                Else : GridUsesrControls.Children.Clear()
                End If

                PanelResults.Visibility = Windows.Visibility.Visible
                If l_movie.Events.Count = 0 Then
                    RBEventResults.IsEnabled = False
                    RBEndMovieResults.IsChecked = True
                    GridEventPRoperties.Children.Clear()
                Else
                    RBEndMovieResults.IsEnabled = True
                    RBEventResults.IsEnabled = True
                    ListViewMovieEvents.SelectedItem = l_movie.Events.First
                End If
            Else
                RBGlobalClickEvents.IsChecked = True
                RBMovieClickEvents.IsEnabled = False
                MediaElement1.Stop()
                MediaElement1.Source = New Uri(l_mediaFile.Path)
                '   PanelResults.Visibility = Windows.Visibility.Visible

                If m_GameInfo.GlobalEvents.Count > 0 Then
                    RBEventResults.IsEnabled = True
                    RBEndMovieResults.IsEnabled = False
                    RBEventResults.IsChecked = True
                Else
                    PanelResults.Visibility = Windows.Visibility.Hidden
                    GridEventPRoperties.Children.Clear()
                End If
            End If
        Catch ex As Exception

        End Try

     
    End Sub

    Private Sub RadioButton_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim l_RadioButton = CType(sender, Controls.RadioButton)
        Dim l_MediaFileID As Integer = l_RadioButton.Tag
        For Each l_file In m_GameInfo.MediaFiles
            l_file.IsStartingMovie = False
        Next

        Dim l_mediaFile = (From l_media In m_GameInfo.MediaFiles Where l_media.ID = l_MediaFileID Select l_media).Single
        If l_mediaFile.Type = MediaFileType.Movie Then
            m_GameInfo.StartingMovieID = l_MediaFileID
        Else
            MsgBox("Only movies can be set to start the game")
            l_RadioButton.IsChecked = False
        End If

    End Sub

    Private Sub ButtonRedownload_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            Dim l_button = CType(sender, Windows.Controls.Button)
            Dim l_id = CInt(l_button.Tag)
            Dim l_mediaFile = (From l_file In m_GameInfo.MediaFiles Where l_file.ID = l_id Select l_file).Single

            Dim l_fileName = System.IO.Path.GetFileName(l_mediaFile.Url)
            Dim l_Path = Path.Combine(GetTempFolderPath, l_fileName)
            'Dim l_Path = "C:\Users\Gal\Desktop\New Folder"
            If Not Directory.Exists(Path.GetDirectoryName(l_Path)) Then
                Directory.CreateDirectory(Path.GetDirectoryName(l_Path))
            End If

            l_mediaFile.Path = l_Path

            If CType(ListViewMediaFiles.SelectedItem, MediaFile).ID = l_mediaFile.ID Then
                MediaElement1.Source = Nothing
                ListViewMediaFiles.SelectedItem = Nothing
            End If
            If Not ReDownloadFile(l_mediaFile) Then
                MsgBox("Failed to download file :")
            Else
                ListViewMediaFiles.SelectedItem = l_mediaFile
                MsgBox("Successfully downloaded file")
            End If

        Catch ex As Exception
            MsgBox("Failed to download file: " & ex.ToString)
        End Try
       
    End Sub

#End Region

#Region "Events Panel"
    Private Sub RBGlobalClickEvents_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            GridEventPRoperties.Children.Clear()
            ListViewGlobalEvents.Visibility = Windows.Visibility.Visible
            ListViewMovieEvents.Visibility = Windows.Visibility.Collapsed
            ListViewGlobalEvents.ItemsSource = New List(Of EventBase)(m_GameInfo.GlobalEvents)

            If m_GameInfo.GlobalEvents.Count > 0 Then
                ListViewGlobalEvents.SelectedItem = m_GameInfo.GlobalEvents.First
                OnListViewGlobalEventsSelectionChanged()
                PanelResults.Visibility = Windows.Visibility.Visible

            Else
                'if its a movie allow end of movie results
                Dim l_mediafile = CType(ListViewMediaFiles.SelectedItem, MediaFile)
                If l_mediafile.Type = MediaFileType.Movie Then
                    Dim l_movie = CType(l_mediafile, Movie)
                    PanelResults.Visibility = Windows.Visibility.Visible
                    RBEndMovieResults.IsChecked = True
                    RBEndMovieResults.IsEnabled = True
                    RBEventResults.IsEnabled = False
                    ListViewResults.ItemsSource = New List(Of Result)(l_movie.EndOfMovieResults)
                Else
                    PanelResults.Visibility = Windows.Visibility.Hidden
                End If

                ' ListViewResults.ItemsSource = Nothing
                ' PanelResults.Visibility = Windows.Visibility.Hidden
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub RBMovieClickEvents_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            ListViewGlobalEvents.Visibility = Windows.Visibility.Collapsed
            ListViewMovieEvents.Visibility = Windows.Visibility.Visible

            If ListViewMediaFiles.SelectedItem IsNot Nothing Then
                Dim l_mediafile = CType(ListViewMediaFiles.SelectedItem, MediaFile)
                If l_mediafile.Type = MediaFileType.Movie Then
                    Dim l_movie = CType(l_mediafile, Movie)
                    If l_movie.Events.Count > 0 Then
                        ListViewMovieEvents.SelectedItem = l_movie.Events.First
                    Else
                        ListViewResults.ItemsSource = Nothing
                        ' PanelResults.Visibility = Windows.Visibility.Hidden
                    End If
                End If
            End If

        Catch ex As Exception

        End Try

    End Sub

    Private Sub AddEventButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            AddEventButton.IsEnabled = False
            Dim l_top = Math.Round(Canvas.GetTop(rubberBand), 0)
            Dim l_bottom = Math.Round(l_top + rubberBand.Height, 0)
            Dim l_left = Math.Round(Canvas.GetLeft(rubberBand), 0)
            Dim l_right = Math.Round(l_left + rubberBand.Width, 0)
            If l_top < 0 OrElse l_bottom < 0 OrElse l_right < 0 OrElse l_left < 0 OrElse l_top = l_bottom OrElse l_left = l_right Then
                MsgBox("Please draw the rectangle again and click ADD EVENT, rectangle boundaries are out of range")
                Return
            End If

            Dim l_rec As New EventRectangle(New Point(l_left, l_top), New Point(l_right, l_bottom))

            Dim l_event As New EventBase(getIdCounter, l_rec)

            Dim l_rectangle As New Rectangle
            l_rectangle.Stroke = New SolidColorBrush(Colors.LightGreen)

            If l_event.EventType = EventsType.ButtonClick Then
                l_rectangle.Fill = New SolidColorBrush(Colors.LightGray)
            End If

            l_rectangle.Width = Math.Abs(l_rec.TopLeft.X - l_rec.BottomRight.X)
            l_rectangle.Height = Math.Abs(l_rec.TopLeft.Y - l_rec.BottomRight.Y)

            l_event.GuiRectangle = New GuiRectangle(l_rectangle, New Point(l_left, l_top))

            'ListViewErea.ItemsSource = New List(Of EventRectangle.Rectangle)(l_event.EventArea.Rectangles)

            canvas1.Children.Remove(rubberBand)
            rubberBand = Nothing

            If l_event.TimeFrame Is Nothing Then

                Dim l_roundedPos = GetRoundedTimeSpan()
                l_event.TimeFrame = New TimeFrame(l_roundedPos, l_roundedPos.Add(New TimeSpan(0, 0, 10)))

            End If

            'if this is a movie event then add it to list of events
            If RBMovieClickEvents.IsChecked Then
                Dim l_movie As Movie = CType(ListViewMediaFiles.SelectedItem, Movie)
                l_movie.Events.Add(l_event)
                ListViewMovieEvents.ItemsSource = New List(Of EventBase)(l_movie.Events)
                ListViewMovieEvents.SelectedItem = l_event
            Else
                m_GameInfo.GlobalEvents.Add(l_event)
                l_event.EventType = EventsType.Text
                ListViewGlobalEvents.ItemsSource = New List(Of EventBase)(GlobalEvents)
                showGlobalEventsErea()
                ListViewGlobalEvents.SelectedItem = l_event
            End If

            ColorRectangles()
        Catch ex As Exception

        End Try

    End Sub

    Private Sub ButtonRemoveEvents_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            Dim l_event As EventBase

            If RBGlobalClickEvents.IsChecked Then
                If ListViewGlobalEvents.SelectedItem Is Nothing Then
                    MsgBox("No event has been selected for deletion")
                    Return
                Else
                    l_event = CType(ListViewGlobalEvents.SelectedItem, EventBase)
                    m_GameInfo.GlobalEvents.Remove(l_event)
                    ListViewGlobalEvents.ItemsSource = New List(Of EventBase)(m_GameInfo.GlobalEvents)
                End If
            Else
                If ListViewMovieEvents.SelectedItem Is Nothing Then
                    MsgBox("No event has been selected for deletion")
                    Return
                Else
                    l_event = CType(ListViewMovieEvents.SelectedItem, EventBase)
                    Dim l_movie As New Movie
                    l_event = GetEventByID(l_event.EventID, l_movie)
                    l_movie.Events.Remove(l_event)
                    ListViewMovieEvents.ItemsSource = New List(Of EventBase)(l_movie.Events)

                End If
            End If

        Catch ex As Exception

        End Try

    End Sub

    Private Sub ComboTypes_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
        GridEventPRoperties.Children.Clear()
        Dim l_combo = CType(sender, Controls.ComboBox)
        Dim l_movie As Movie
        Dim l_event = GetEventByID(l_combo.Tag, l_movie)
        Try
            Dim l_selectedItem = CType(l_combo.SelectedItem, EventsType)
            If l_selectedItem = EventsType.ButtonClick Then
                l_event.EventType = EventsType.ButtonClick


                l_event.GuiRectangle.Rectangel.Fill = New SolidColorBrush(Colors.LightGray)


                Dim l_ButtonEventProperties As New ButtonClickEventUserControl
                l_ButtonEventProperties.DataContext = l_event
                GridEventPRoperties.Children.Add(l_ButtonEventProperties)
                l_ButtonEventProperties.HorizontalAlignment = Windows.HorizontalAlignment.Left
            ElseIf l_selectedItem = EventsType.HotSpot Then
                l_event.EventType = EventsType.HotSpot
                l_event.GuiRectangle.Rectangel.Fill = Nothing
                l_event.BackgroundColor = Colors.Transparent
                l_event.Text = ""
                l_event.GuiRectangle.TextBlock.Text = ""
            ElseIf l_selectedItem = EventsType.Text Then
                l_event.EventType = EventsType.Text
                l_event.BackroundImageID = 0


            ElseIf l_selectedItem = EventsType.MovablePicture Then
                l_event.Text = ""
                l_event.GuiRectangle.TextBlock.Text = ""
                l_event.GuiRectangle.Rectangel.Fill = Nothing
                l_event.BackgroundColor = Colors.Transparent

                Dim l_AvialableImages As List(Of MediaFile) = (From l_Media In m_GameInfo.MediaFiles Where l_Media.Type = MediaFileType.Image Select l_Media).ToList
                Dim l_MovablePictureControl As New MovablePictureEventConrol(l_AvialableImages)
                l_MovablePictureControl.DataContext = l_event
                GridEventPRoperties.Children.Add(l_MovablePictureControl)


            ElseIf l_selectedItem = EventsType.PictureBox Then
                l_event.Text = ""
                l_event.GuiRectangle.TextBlock.Text = ""
                l_event.GuiRectangle.Rectangel.Fill = Nothing
                l_event.BackgroundColor = Colors.Transparent

                Dim l_AvialableImages As List(Of MediaFile) = (From l_Media In m_GameInfo.MediaFiles Where l_Media.Type = MediaFileType.Image Select l_Media).ToList
                Dim l_PictureBoxEventPropertiesControl As New PictureBoxEventControl(l_AvialableImages)
                l_PictureBoxEventPropertiesControl.DataContext = l_event
                GridEventPRoperties.Children.Add(l_PictureBoxEventPropertiesControl)



            End If

        Catch ex As Exception

        End Try

    End Sub

    Private Sub ButtonStartingAt_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            Dim l_button = CType(sender, Controls.Button)
            l_button.Content = GetRoundedTimeSpan()
        Catch ex As Exception

        End Try
       
    End Sub

    Private Sub ButtonFinishAt_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            Dim l_button = CType(sender, Controls.Button)

            l_button.Content = GetRoundedTimeSpan()
        Catch ex As Exception

        End Try
    

    End Sub

    Private Sub Text_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
        Try
            Dim l_movie As Movie
            Dim l_textbox = CType(sender, Controls.TextBox)

            Dim l_event = GetEventByID(l_textbox.Tag, l_movie)
            If l_event.EventType = EventsType.MovablePicture Then
                MsgBox("Movable Picture does not contain text")
                Return
            ElseIf l_event.EventType = EventsType.HotSpot Then
                MsgBox("Touch Screen event does not contain text")
                Return
            End If

            l_event.Text = l_textbox.Text
            l_event.GuiRectangle.TextBlock.Text = l_event.Text
            l_event.GuiRectangle.TextBlock.FontStretch = FontStretches.Expanded

        Catch ex As Exception

        End Try

    End Sub

    Private Sub textBlockOnClickColor_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            Dim l_movie As Movie = Nothing
            Dim l_textblock = CType(sender, Controls.Button)
            Dim l_Event = GetEventByID(l_textblock.Tag, l_movie)
            If l_Event IsNot Nothing Then

                Dim l = New System.Windows.Forms.ColorDialog
                If l.ShowDialog = Forms.DialogResult.OK Then
                    Dim l_color = l.Color

                    Dim l_mediaColor = System.Windows.Media.Color.FromArgb(l_color.A, l_color.R, l_color.G, l_color.B)
                    l_Event.OnClickEfectColor = l_mediaColor
                    l_textblock.Background = New SolidColorBrush(l_mediaColor)

                End If


            End If
        Catch ex As Exception

        End Try
       
    End Sub

    Private Sub textBlockBackground_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

        Dim l_movie As Movie = Nothing
        Dim l_textblock = CType(sender, Controls.Button)
        Dim l_Event = GetEventByID(l_textblock.Tag, l_movie)
        If l_Event IsNot Nothing Then
            If l_Event.EventType = EventsType.HotSpot Then
                MsgBox("Touch screen event has no background...")
                Return

            End If

            If l_Event.EventType = EventsType.MovablePicture OrElse l_Event.EventType = EventsType.PictureBox Then
                Dim l_Images = (From l_Media In m_GameInfo.MediaFiles Where l_Media.Type = MediaFileType.Image Select l_Media).ToList
                Dim l_SelectImageDialog As New SelectImageIdControl(l_Images)
                l_SelectImageDialog.Owner = Me
                If l_SelectImageDialog.ShowDialog Then
                    Dim l_ImageID As Integer = l_SelectImageDialog.SelectedImageID
                    l_textblock.Content = l_ImageID
                    Dim l_ImagePath = l_SelectImageDialog.selectedImagePath
                    'set the brush for the rectangle

                    Dim l_imgs As New ImageSourceConverter
                    Dim l_brush As New ImageBrush

                    Dim l_ImageSource = CType(l_imgs.ConvertFromString(l_ImagePath), ImageSource)
                    l_brush.ImageSource = l_ImageSource

                    l_Event.GuiRectangle.Rectangel.Fill = l_brush

                    Return
                Else
                    Return
                End If
            End If


            Dim l = New System.Windows.Forms.ColorDialog
            If l.ShowDialog = Forms.DialogResult.OK Then
                Dim l_color = l.Color

                Dim l_mediaColor = System.Windows.Media.Color.FromArgb(l_color.A, l_color.R, l_color.G, l_color.B)
                l_Event.BackgroundColor = l_mediaColor
                l_textblock.Background = New SolidColorBrush(l_mediaColor)
                l_Event.GuiRectangle.Rectangel.Fill = New SolidColorBrush(l_mediaColor)

            End If


        End If
    End Sub

    'Private Sub textBlockBackground_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
    '    Dim l_movie As Movie = Nothing
    '    Dim l_textblock = CType(sender, TextBlock)
    '    Dim l_Event = GetEventByID(l_textblock.Tag, l_movie)
    '    If l_Event IsNot Nothing Then
    '        If l_Event.BackgroundType = BackgroundType.Color Then

    '            Dim l = New System.Windows.Forms.ColorDialog
    '            l.AllowFullOpen = True
    '            l.SolidColorOnly = False
    '            If l.ShowDialog = Forms.DialogResult.OK Then
    '                Dim l_color = l.Color
    '            End If
    '        End If

    '    End If
    'End Sub

    Private Sub Button2ndLocation_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

        Dim l_button = CType(sender, Controls.Button)
        Dim l_movie = Nothing
        Dim l_event = GetEventByID(l_button.Tag, l_movie)

        If l_event.EventType <> EventsType.MovablePicture Then
            MsgBox("This property is for movable picture only")
            Return
        End If

        If rubberBand IsNot Nothing AndAlso canvas1.Children.Contains(rubberBand) Then
            Dim l_top = Math.Round(Canvas.GetTop(rubberBand), 0)
            Dim l_bottom = Math.Round(l_top + rubberBand.Height, 0)
            Dim l_left = Math.Round(Canvas.GetLeft(rubberBand), 0)
            Dim l_right = Math.Round(l_left + rubberBand.Width, 0)

            Dim l_rec As New EventRectangle(New Point(l_left, l_top), New Point(l_right, l_bottom))

            l_button.Content = l_rec.ToString


            l_event.SecondaryLocation = l_rec

        End If


    End Sub

    Private Sub ListViewGlobalEvents_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)


        OnListViewGlobalEventsSelectionChanged()


    End Sub
    Private Sub OnListViewGlobalEventsSelectionChanged()
        Try
            Dim l_event As EventBase = CType(ListViewGlobalEvents.SelectedItem, EventBase)

            If l_event IsNot Nothing Then
                Dim l_mediafile = CType(ListViewMediaFiles.SelectedItem, MediaFile)
                If l_mediafile.Type = MediaFileType.Movie Then
                    RBEndMovieResults.IsEnabled = True
                    RBEventResults.IsEnabled = True
                Else
                    RBEndMovieResults.IsEnabled = False
                End If

                RBEventResults.IsChecked = True
                ' PanelResults.Visibility = Windows.Visibility.Visible
                ListViewResults.ItemsSource = New List(Of Result)(l_event.YesResultsList)

                If ListViewResults.Items.Count > 0 Then
                    ListViewResults.SelectedItem = ListViewResults.Items(0)
                Else : GridUsesrControls.Children.Clear()
                End If

            End If
        Catch ex As Exception

        End Try

    End Sub

    Private Sub ListViewMovieEvents_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)

        Try
            Dim l_event As EventBase = CType(ListViewMovieEvents.SelectedItem, EventBase)

            If l_event IsNot Nothing Then
                RBEventResults.IsChecked = True
                RBEventResults.IsEnabled = True
                RBEndMovieResults.IsEnabled = True
                RBResultYes.IsChecked = True
                ListViewResults.ItemsSource = l_event.YesResultsList
                If ListViewResults.Items.Count > 0 Then
                    ListViewResults.SelectedItem = ListViewResults.Items(0)
                Else : GridUsesrControls.Children.Clear()
                End If
                '  PanelResults.Visibility = Windows.Visibility.Visible

                'set the properties controls
                GridEventPRoperties.Children.Clear()
                Dim l_control As Controls.UserControl = Nothing
                If l_event.EventType = EventsType.ButtonClick Then
                    l_control = New ButtonClickEventUserControl
                ElseIf l_event.EventType = EventsType.MovablePicture Then
                    Dim l_AvialableImages As List(Of MediaFile) = (From l_Media In m_GameInfo.MediaFiles Where l_Media.Type = MediaFileType.Image Select l_Media).ToList
                    l_control = New MovablePictureEventConrol(l_AvialableImages)
                ElseIf l_event.EventType = EventsType.PictureBox Then
                    Dim l_AvialableImages As List(Of MediaFile) = (From l_Media In m_GameInfo.MediaFiles Where l_Media.Type = MediaFileType.Image Select l_Media).ToList
                    l_control = New PictureBoxEventControl(l_AvialableImages)
                ElseIf l_event.EventType = EventsType.Text Then
                    l_control = New TextEventPropertiesControl
                End If

                If l_control IsNot Nothing Then
                    l_control.DataContext = l_event
                    GridEventPRoperties.Children.Add(l_control)
                End If

            End If
        Catch ex As Exception

        End Try
        
    End Sub

#End Region

#Region "Results Panel"
    Private Sub RBEndMovieResults_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            If ListViewMediaFiles.SelectedItem IsNot Nothing Then
                Dim l_MediaFile = CType(ListViewMediaFiles.SelectedItem, MediaFile)
                If l_MediaFile.Type = MediaFileType.Movie Then
                    Dim l_movie = CType(l_MediaFile, Movie)
                    ListViewResults.ItemsSource = New List(Of Result)(l_movie.EndOfMovieResults)
                    If ListViewResults.Items.Count > 0 Then
                        ListViewResults.SelectedItem = ListViewResults.Items(0)
                    Else : GridUsesrControls.Children.Clear()
                    End If
                End If
            End If
        Catch ex As Exception

        End Try
        PanelResultsYesNo.Visibility = Windows.Visibility.Collapsed
    End Sub

    Private Sub RBEventResults_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            If RBGlobalClickEvents.IsChecked Then
                If ListViewGlobalEvents.SelectedItem IsNot Nothing Then
                    Dim l_Event = CType(ListViewGlobalEvents.SelectedItem, EventBase)
                    ListViewResults.ItemsSource = New List(Of Result)(l_Event.YesResultsList)
                    If ListViewResults.Items.Count > 0 Then
                        ListViewResults.SelectedItem = ListViewResults.Items(0)
                    Else : GridUsesrControls.Children.Clear()
                    End If
                End If
            ElseIf RBEventResults.IsChecked Then
                If ListViewMovieEvents.SelectedItem IsNot Nothing Then
                    Dim l_Event = CType(ListViewMovieEvents.SelectedItem, EventBase)
                    ListViewResults.ItemsSource = New List(Of Result)(l_Event.YesResultsList)
                    If ListViewResults.Items.Count > 0 Then
                        ListViewResults.SelectedItem = ListViewResults.Items(0)
                    Else : GridUsesrControls.Children.Clear()
                    End If
                End If
            End If
            PanelResultsYesNo.Visibility = Windows.Visibility.Visible
            RBResultYes.IsChecked = True
        Catch ex As Exception

        End Try
      
    End Sub

    Private Sub RBResultYes_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            Dim l_SelectedEvent = getSelectedEvent()
            If l_SelectedEvent IsNot Nothing Then
                ListViewResults.ItemsSource = l_SelectedEvent.YesResultsList
                If ListViewResults.Items.Count > 0 Then
                    ListViewResults.SelectedItem = ListViewResults.Items(0)
                Else : GridUsesrControls.Children.Clear()
                End If
            Else
                MsgBox("no selected event")
            End If
        Catch ex As Exception

        End Try
      
    End Sub

    Private Sub RBResultNo_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            Dim l_SelectedEvent = getSelectedEvent()
            If l_SelectedEvent IsNot Nothing Then
                ListViewResults.ItemsSource = l_SelectedEvent.NoResultsList
                If ListViewResults.Items.Count > 0 Then
                    ListViewResults.SelectedItem = ListViewResults.Items(0)
                Else : GridUsesrControls.Children.Clear()
                End If
            Else
                MsgBox("no selected event")
            End If
        Catch ex As Exception

        End Try
    
    End Sub

    Private Sub ButtonDeleteResult_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            If ListViewResults.SelectedItem Is Nothing Then
                MsgBox("No Result has been selected for deletion")
                Return
            End If
            Dim l_result = CType(ListViewResults.SelectedItem, Result)

            If RBEndMovieResults.IsChecked Then
                If ListViewMediaFiles.SelectedItem IsNot Nothing Then
                    Dim l_mediaFile = CType(ListViewMediaFiles.SelectedItem, MediaFile)
                    If l_mediaFile.Type = MediaFileType.Movie Then
                        Dim l_movie = CType(l_mediaFile, Movie)
                        Try
                            l_movie.EndOfMovieResults.Remove(l_result)
                        Catch ex As Exception
                            MsgBox("Failed to delete this result")
                        End Try
                    Else
                        MsgBox("Failed to delet this result, movie is not selected")
                    End If

                End If
            Else
                'this is an event result list
                If RBGlobalClickEvents.IsChecked Then
                    Try
                        Dim l_globalEvent = CType(ListViewGlobalEvents.SelectedItem, EventBase)
                        If RBResultYes.IsChecked Then
                            l_globalEvent.YesResultsList.Remove(l_result)
                            ListViewResults.ItemsSource = New List(Of Result)(l_globalEvent.YesResultsList)
                            If ListViewResults.Items.Count > 0 Then
                                ListViewResults.SelectedItem = ListViewResults.Items(0)
                            Else : GridUsesrControls.Children.Clear()
                            End If
                        ElseIf RBResultNo.IsChecked Then
                            l_globalEvent.NoResultsList.Remove(l_result)
                            ListViewResults.ItemsSource = New List(Of Result)(l_globalEvent.NoResultsList)
                            If ListViewResults.Items.Count > 0 Then
                                ListViewResults.SelectedItem = ListViewResults.Items(0)
                            Else : GridUsesrControls.Children.Clear()
                            End If
                        End If

                    Catch ex As Exception
                        MsgBox("failed to delete result")
                    End Try
                Else
                    Try
                        Dim l_Event = CType(ListViewMovieEvents.SelectedItem, EventBase)
                        If RBResultYes.IsChecked Then
                            l_Event.YesResultsList.Remove(l_result)
                            ListViewResults.ItemsSource = New List(Of Result)(l_Event.YesResultsList)
                            If ListViewResults.Items.Count > 0 Then
                                ListViewResults.SelectedItem = ListViewResults.Items(0)
                            Else : GridUsesrControls.Children.Clear()
                            End If
                        Else
                            l_Event.NoResultsList.Remove(l_result)
                            ListViewResults.ItemsSource = New List(Of Result)(l_Event.NoResultsList)
                            If ListViewResults.Items.Count > 0 Then
                                ListViewResults.SelectedItem = ListViewResults.Items(0)
                            Else : GridUsesrControls.Children.Clear()
                            End If
                        End If
                    Catch ex As Exception

                    End Try


                End If
            End If
        Catch ex As Exception

        End Try
       
    End Sub

    Private Sub ButtonAddResult_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            Dim l_Event As EventBase = Nothing

            If RBEndMovieResults.IsChecked Then
                If ListViewMediaFiles.SelectedItem IsNot Nothing AndAlso CType(ListViewMediaFiles.SelectedItem, MediaFile).Type = MediaFileType.Movie Then
                    Dim l_movie = CType(ListViewMediaFiles.SelectedItem, Movie)
                    l_movie.EndOfMovieResults.Add(New Result(getIdCounter))
                    ListViewResults.ItemsSource = New List(Of Result)(l_movie.EndOfMovieResults)
                    If ListViewResults.Items.Count > 0 Then
                        ListViewResults.SelectedItem = ListViewResults.Items(0)
                    Else : GridUsesrControls.Children.Clear()
                    End If
                End If
                Return
            End If
            If RBGlobalClickEvents.IsChecked Then
                'If ListViewGlobalEvents.SelectedItem IsNot Nothing Then
                '    l_Event = CType(ListViewGlobalEvents.SelectedItem, EventBase)
                'End If
                MsgBox("Global events currently have no effects")
                Return
            Else
                If ListViewMovieEvents.SelectedItem IsNot Nothing Then
                    l_Event = CType(ListViewMovieEvents.SelectedItem, EventBase)
                End If
            End If

            If RBResultYes.IsChecked Then
                l_Event.YesResultsList.Add(New Result(getIdCounter))
                ListViewResults.ItemsSource = New List(Of Result)(l_Event.YesResultsList)
                If ListViewResults.Items.Count > 0 Then
                    ListViewResults.SelectedItem = ListViewResults.Items(0)
                Else : GridUsesrControls.Children.Clear()
                End If
            ElseIf RBResultNo.IsChecked Then
                l_Event.NoResultsList.Add(New Result(getIdCounter))
                ListViewResults.ItemsSource = New List(Of Result)(l_Event.NoResultsList)
                If ListViewResults.Items.Count > 0 Then
                    ListViewResults.SelectedItem = ListViewResults.Items(0)
                Else : GridUsesrControls.Children.Clear()
                End If
            End If

        Catch ex As Exception

        End Try
       
    End Sub

    Private Sub ComboActionTypes_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)

        Try
            Dim l_Event As EventBase = Nothing
            Dim l_Result As Result = Nothing
            Dim l_combo = CType(sender, Controls.ComboBox)

            If RBEventResults.IsChecked Then
                If RBGlobalClickEvents.IsChecked Then
                    If ListViewGlobalEvents.SelectedItem IsNot Nothing Then
                        l_Event = CType(ListViewGlobalEvents.SelectedItem, EventBase)
                    End If
                Else
                    If ListViewMovieEvents.SelectedItem IsNot Nothing Then
                        l_Event = CType(ListViewMovieEvents.SelectedItem, EventBase)
                    End If
                End If


                l_Result = (From l_Resul In l_Event.YesResultsList Where l_Resul.ResultID = l_combo.Tag Select l_Resul).SingleOrDefault
                If l_Result Is Nothing OrElse l_Result.ResultID = 0 Then
                    l_Result = (From l_Resul In l_Event.NoResultsList Where l_Resul.ResultID = l_combo.Tag Select l_Resul).SingleOrDefault
                End If
                ListViewResults.SelectedItem = l_Result
            ElseIf RBEndMovieResults.IsChecked Then
                If ListViewMediaFiles.SelectedItem IsNot Nothing Then
                    Dim l_mediafile = CType(ListViewMediaFiles.SelectedItem, MediaFile)
                    If l_mediafile.Type = MediaFileType.Movie Then
                        Dim l_movie = CType(l_mediafile, Movie)
                        l_Result = (From l_resul In l_movie.EndOfMovieResults Where l_resul.ResultID = l_combo.Tag Select l_resul).Single
                        ListViewResults.SelectedItem = l_Result
                    End If
                End If
            End If


            ' Dim l_result = CType(ListViewResults.SelectedItem, Result)
            Dim l_ResProperties As IresultProperties = Nothing
            If l_Result IsNot Nothing Then

                If l_Result.ResultAction = ResultAction.moveToMovie Then
                    If l_Result.ResultProperties Is Nothing OrElse Not TypeOf l_Result.ResultProperties Is MoveToMovieResultProperties Then

                        l_ResProperties = New MoveToMovieResultProperties
                        l_Result.ResultProperties = l_ResProperties
                    End If


                ElseIf l_Result.ResultAction = ResultAction.showPicture Then
                    If l_Result.ResultProperties Is Nothing OrElse Not TypeOf l_Result.ResultProperties Is ShowPictureResultProperties Then
                        l_ResProperties = New ShowPictureResultProperties
                        l_Result.ResultProperties = l_ResProperties
                    End If

                ElseIf l_Result.ResultAction = ResultAction.changeGlobalElementText Then
                    If l_Result.ResultProperties Is Nothing OrElse Not TypeOf l_Result.ResultProperties Is ChangeGlobalEventTextResultProperties Then
                        l_ResProperties = New ChangeGlobalEventTextResultProperties
                        l_Result.ResultProperties = l_ResProperties
                    End If

                ElseIf l_Result.ResultAction = ResultAction.playAudio Then
                    If l_Result.ResultProperties Is Nothing OrElse Not TypeOf l_Result.ResultProperties Is PlaySoundResultProperties Then
                        l_ResProperties = New PlaySoundResultProperties
                        l_Result.ResultProperties = l_ResProperties
                    End If
                End If


            End If
        Catch ex As Exception

        End Try


    End Sub

    Private Sub ListViewResults_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
        Try
            Dim l_result = CType(ListViewResults.SelectedItem, Result)
            If l_result Is Nothing Then
                Return
            End If
            'For Each l_child In GridUsesrControls.Children
            '    Try
            '        Dim l_control = CType(l_child, UserControl)
            '        'l_control.Visibility = Windows.Visibility.Collapsed
            '        GridUsesrControls.Children.Clear()
            '    Catch ex As Exception

            '    End Try

            'Next
            GridUsesrControls.Children.Clear()

            If l_result.ResultAction = ResultAction.moveToMovie Then
                Dim l_availableMovies = (From l_movie In m_GameInfo.MediaFiles Where l_movie.Type = MediaFileType.Movie Select CType(l_movie, Movie)).ToList
                Dim l_control As Controls.UserControl = New MoveToMoviePropertiesControl(l_availableMovies)
                GridUsesrControls.Children.Add(l_control)
                l_control.HorizontalAlignment = Windows.HorizontalAlignment.Left
                l_control.VerticalAlignment = Windows.VerticalAlignment.Center
                l_control.Visibility = Windows.Visibility.Visible
                l_control.DataContext = CType(l_result.ResultProperties, MoveToMovieResultProperties)
            ElseIf l_result.ResultAction = ResultAction.changeGlobalElementText Then
                Dim l_AvilableEvents As List(Of Integer) = (From l_event In m_GameInfo.GlobalEvents Select l_event.EventID).ToList
                Dim l_control As Controls.UserControl = New ChangeGlobalElementControl(l_AvilableEvents)
                GridUsesrControls.Children.Add(l_control)
                l_control.HorizontalAlignment = Windows.HorizontalAlignment.Left
                l_control.VerticalAlignment = Windows.VerticalAlignment.Center
                l_control.Visibility = Windows.Visibility.Visible
                l_control.DataContext = CType(l_result.ResultProperties, ChangeGlobalEventTextResultProperties)

            ElseIf l_result.ResultAction = ResultAction.playAudio Then
                Dim l_AvilableAudio As List(Of Integer) = (From l_audio In m_GameInfo.MediaFiles Where l_audio.Type = MediaFileType.Sound Select l_audio.ID).ToList
                Dim l_control As Controls.UserControl = New PlaySoundResultPropertiesControl(l_AvilableAudio)
                GridUsesrControls.Children.Add(l_control)
                l_control.HorizontalAlignment = Windows.HorizontalAlignment.Left
                l_control.VerticalAlignment = Windows.VerticalAlignment.Center
                l_control.Visibility = Windows.Visibility.Visible
                l_control.DataContext = CType(l_result.ResultProperties, PlaySoundResultProperties)

            ElseIf l_result.ResultAction = ResultAction.showPicture Then
                Dim l_AvialableImages As List(Of MediaFile) = (From l_Media In m_GameInfo.MediaFiles Where l_Media.Type = MediaFileType.Image Select l_Media).ToList
                Dim l_control As Controls.UserControl = New ShowPictureResultPropertiesControl(l_AvialableImages)
                GridUsesrControls.Children.Add(l_control)
                l_control.HorizontalAlignment = Windows.HorizontalAlignment.Left
                l_control.VerticalAlignment = Windows.VerticalAlignment.Center
                l_control.Visibility = Windows.Visibility.Visible
                l_control.DataContext = CType(l_result.ResultProperties, ShowPictureResultProperties)
                l_control.VerticalAlignment = Windows.VerticalAlignment.Top
                l_control.HorizontalAlignment = Windows.HorizontalAlignment.Left
            End If
        Catch ex As Exception

        End Try
       
    End Sub

#End Region


#Region "Private Methods"

    Private Function ReDownloadFile(ByVal p_mediaFile As MediaFile) As Boolean
        Dim l_success = DownloadFile(p_mediaFile.Url, p_mediaFile.Path)
        Return l_success

    End Function

    Private Function GetMediaFileTypeFromString(ByVal p_StringType As String) As MediaFileType
        Try
            If p_StringType.Equals(MediaFileType.Image.ToString) Then
                Return MediaFileType.Image
            ElseIf p_StringType.Equals(MediaFileType.Movie.ToString) Then
                Return MediaFileType.Movie
            ElseIf p_StringType.Equals(MediaFileType.Sound.ToString) Then
                Return MediaFileType.Sound
            End If
        Catch ex As Exception

        End Try

    End Function

    Public Event PropertyChanged As PropertyChangedEventHandler _
      Implements INotifyPropertyChanged.PropertyChanged

    Private Sub NotifyPropertyChanged(ByVal info As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
    End Sub

    Private Function GetRoundedTimeSpan()
        Try
            Dim l_newPos = New TimeSpan()
            Dim l_OriginalPos = MediaElement1.Position

            Dim l_RoundedPos As New TimeSpan
            'If l_OriginalPos.Milliseconds > 500 Then
            '    l_RoundedPos = New TimeSpan(l_OriginalPos.Hours, l_OriginalPos.Minutes, l_OriginalPos.Seconds + 1)
            'Else
            '    l_RoundedPos = New TimeSpan(l_OriginalPos.Hours, l_OriginalPos.Minutes, l_OriginalPos.Seconds)
            'End If
            l_RoundedPos = New TimeSpan(l_OriginalPos.Days, l_OriginalPos.Hours, l_OriginalPos.Minutes, l_OriginalPos.Seconds, l_OriginalPos.Milliseconds)
            Return l_RoundedPos
        Catch ex As Exception

        End Try

    End Function

    Private Function getSelectedEvent() As EventBase
        Dim l_event As EventBase = Nothing
        Try
            If RBGlobalClickEvents.IsChecked Then
                If ListViewGlobalEvents.SelectedItem IsNot Nothing Then
                    l_event = CType(ListViewGlobalEvents.SelectedItem, EventBase)
                End If
            ElseIf RBMovieClickEvents.IsChecked Then
                If ListViewMovieEvents.SelectedItem IsNot Nothing Then
                    l_event = CType(ListViewMovieEvents.SelectedItem, EventBase)
                End If
            End If
        Catch ex As Exception

        End Try
        Return l_event
    End Function



    Private Function App_Path() As String
        Return System.AppDomain.CurrentDomain.BaseDirectory()
    End Function

    Private Function GetTempFolderPath() As String
        ' Return Path.Combine(Directory.GetParent(Directory.GetParent(Directory.GetParent(App_Path).ToString).ToString).ToString, "TempMovieFolder")
        Return Path.Combine(App_Path, "TempMovieFolder")
    End Function

    Private Function DownloadFile(ByVal sSourceUrl As String, _
                              ByVal sLocalFile As String) As Boolean

        'Download the file. BINDF_GETNEWESTVERSION forces 
        'the API to download from the specified source. 
        'Passing 0& as dwReserved causes the locally-cached 
        'copy to be downloaded, if available. If the API 
        'returns ERROR_SUCCESS (0), DownloadFile returns True.
        DownloadFile = URLDownloadToFile(0&, _
                                         sSourceUrl, _
                                         sLocalFile, _
                                         BINDF_GETNEWESTVERSION, _
                                         0&) = ERROR_SUCCESS

    End Function

    Private Declare Function URLDownloadToFile Lib "urlmon" _
 Alias "URLDownloadToFileA" _
(ByVal pCaller As Integer, _
 ByVal szURL As String, _
 ByVal szFileName As String, _
 ByVal dwReserved As Integer, _
 ByVal lpfnCB As Integer) As Integer

    Private Const ERROR_SUCCESS As Long = 0
    Private Const BINDF_GETNEWESTVERSION As Long = &H10
    Private Const INTERNET_FLAG_RELOAD As Long = &H80000000


    Private Function getIdCounter() As Integer
        m_idCounter += 1
        Return m_idCounter
    End Function

    Private Function GetEventByID(ByVal p_eventID As Integer, ByRef p_movie As Movie) As EventBase
        For Each l_mediaFile In m_GameInfo.MediaFiles
            If l_mediaFile.Type = MediaFileType.Movie Then
                Dim l_movie As Movie = CType(l_mediaFile, Movie)
                For Each l_ev In l_movie.Events
                    If l_ev.EventID = p_eventID Then
                        p_movie = l_movie
                        Return l_ev
                    End If
                Next
            End If
            For Each l_Ev In m_GameInfo.GlobalEvents
                If l_Ev.EventID = p_eventID Then
                    p_movie = Nothing
                    Return l_Ev
                End If
            Next
            'Return Nothing
        Next
        Return Nothing
    End Function

#Region "Events Area"

#Region "rubber - rectangles"
    Private Sub test_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Me.MouseDown
        If Not canvas1.IsMouseCaptured Then
            mouseLeftDownPoint = e.GetPosition(canvas1)
            canvas1.CaptureMouse()
        End If
    End Sub


    Private Sub test_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles Me.MouseMove
        If (canvas1.IsMouseCaptured) Then
            Dim l_currentPoint As Point = e.GetPosition(canvas1)
            If rubberBand Is Nothing Then
                rubberBand = New Rectangle
                rubberBand.Stroke = New SolidColorBrush(Colors.LightGray)
                canvas1.Children.Add(rubberBand)
            End If
            Dim l_width = Math.Abs(mouseLeftDownPoint.X - l_currentPoint.X)
            Dim l_height = Math.Abs(mouseLeftDownPoint.Y - l_currentPoint.Y)
            Dim l_Left = Math.Min(mouseLeftDownPoint.X, l_currentPoint.X)
            Dim l_top = Math.Min(mouseLeftDownPoint.Y, l_currentPoint.Y)

            rubberBand.Width = l_width
            rubberBand.Height = l_height
            Canvas.SetLeft(rubberBand, l_Left)
            Canvas.SetTop(rubberBand, l_top)


        End If
    End Sub


    Private Sub test_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Me.MouseUp
        If canvas1.IsMouseCaptured AndAlso rubberBand IsNot Nothing Then
            Dim l_filling As SolidColorBrush = New SolidColorBrush(Colors.Blue)
            rubberBand.Fill = l_filling
            rubberBand.Fill.Opacity = 0.25



            'canvas1.Children.Remove(rubberBand)
            'rubberBand = Nothing
            canvas1.ReleaseMouseCapture()
            If ListViewMediaFiles.SelectedItem IsNot Nothing AndAlso RBMovieClickEvents.IsChecked Then
                AddEventButton.IsEnabled = True
            ElseIf RBGlobalClickEvents.IsChecked Then
                AddEventButton.IsEnabled = True

            End If

        End If
    End Sub

#End Region



    Private Sub ButtonDeleteSquare_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        'If ListViewErea.SelectedItem Is Nothing Then
        '    Return
        'End If

        'Dim l_Event = CType(ListViewEvents.SelectedItem, EventBase)
        'Dim l_rec = CType(ListViewErea.SelectedItem, EventRectangle)

        'l_Event.EventArea.Remove(l_rec)
        'Dim l_guirec = (From guRec In l_Event.GuiRectangles Where guRec.TopLeft.Equals(l_rec.TopLeft) Select guRec).SingleOrDefault
        'Try
        '    l_Event.GuiRectangles.Remove(l_guirec)
        '    canvas1.Children.Remove(l_guirec.Rectangel)
        'Catch ex As Exception

        'End Try


        'ListViewErea.ItemsSource = l_Event.EventArea.Rectangles

    End Sub

    Public Delegate Sub ColorRectsDel()

    Private Sub ColorRectangles()
        Try
            If ListViewMediaFiles.SelectedItem IsNot Nothing Then
                Dim l_MediaFile = CType(ListViewMediaFiles.SelectedItem, MediaFile)
                If l_MediaFile.Type = MediaFileType.Movie Then
                    Dim l_movie = CType(ListViewMediaFiles.SelectedItem, Movie)
                    For Each l_Event In l_movie.Events
                        Dim l_isEventNow As Boolean = False

                        If MediaElement1.Position >= l_Event.TimeFrame.FromTime AndAlso MediaElement1.Position <= l_Event.TimeFrame.ToTime Then
                            l_isEventNow = True
                            ' Exit For
                        End If

                        If l_isEventNow Then
                            If ListViewMovieEvents.SelectedItem IsNot Nothing AndAlso CType(ListViewMovieEvents.SelectedItem, EventBase).EventID = l_Event.EventID Then
                                ShowEventErea(l_Event, Colors.LightSkyBlue)
                            Else
                                ShowEventErea(l_Event, Colors.LightGreen)
                            End If

                        Else
                            RemoveEventErea(l_Event)
                        End If
                    Next
                Else
                    canvas1.Children.Clear()
                    showGlobalEventsErea()
                End If

            End If
        Catch ex As Exception
            MsgBox("error" & ex.ToString)
        End Try

    End Sub

    Private Sub ShowEventErea(ByVal p_event As EventBase, ByVal p_color As Color)

        Dim l_rectangle = p_event.GuiRectangle
        Try
            If Not canvas1.Children.Contains(l_rectangle.Rectangel) Then
                l_rectangle.Rectangel.Stroke = New SolidColorBrush(p_color)
                canvas1.Children.Add(l_rectangle.Rectangel)

                Canvas.SetLeft(l_rectangle.Rectangel, l_rectangle.TopLeft.X)
                Canvas.SetTop(l_rectangle.Rectangel, l_rectangle.TopLeft.Y)

                'add the text block
                If p_event.EventType = EventsType.WheelLeft Then
                    l_rectangle.TextBlock.Text = "Wheel Left"
                ElseIf p_event.EventType = EventsType.WheelRight Then
                    l_rectangle.TextBlock.Text = "Wheel Right"
                ElseIf p_event.EventType = EventsType.Shake Then
                    l_rectangle.TextBlock.Text = "Shake"
                End If
                canvas1.Children.Add(l_rectangle.TextBlock)

                Canvas.SetLeft(l_rectangle.TextBlock, l_rectangle.TopLeft.X)
                Canvas.SetTop(l_rectangle.TextBlock, l_rectangle.TopLeft.Y)


                'm_ShownRectangles.Add(l_rectangle)
            Else
                l_rectangle.Rectangel.Stroke = New SolidColorBrush(p_color)
                'add the text block
                If p_event.EventType = EventsType.WheelLeft Then
                    l_rectangle.TextBlock.Text = "Wheel Left"
                ElseIf p_event.EventType = EventsType.WheelRight Then
                    l_rectangle.TextBlock.Text = "Wheel Right"
                ElseIf p_event.EventType = EventsType.Shake Then
                    l_rectangle.TextBlock.Text = "Shake"
                End If
            End If

        Catch ex As Exception

        End Try


    End Sub

    Private Sub ChangeEventRectanglesColor(ByVal p_event As EventBase, ByVal p_color As Color)
        p_event.GuiRectangle.Rectangel.Stroke = New SolidColorBrush(p_color)

    End Sub

    Private Sub RemoveEventErea(ByVal p_event As EventBase)
        Try
            canvas1.Children.Remove(p_event.GuiRectangle.Rectangel)
            canvas1.Children.Remove(p_event.GuiRectangle.TextBlock)
        Catch ex As Exception

        End Try

    End Sub

    Private Sub showGlobalEventsErea()
        For Each l_event In m_GameInfo.GlobalEvents
            Dim l_rectangle = l_event.GuiRectangle
            Try
                If Not canvas1.Children.Contains(l_rectangle.Rectangel) Then
                    ' l_rectangle.Rectangel.Stroke = New SolidColorBrush()
                    canvas1.Children.Add(l_rectangle.Rectangel)

                    Canvas.SetLeft(l_rectangle.Rectangel, l_rectangle.TopLeft.X)
                    Canvas.SetTop(l_rectangle.Rectangel, l_rectangle.TopLeft.Y)

                    'add the text block
                    canvas1.Children.Add(l_rectangle.TextBlock)

                    Canvas.SetLeft(l_rectangle.TextBlock, l_rectangle.TopLeft.X)
                    Canvas.SetTop(l_rectangle.TextBlock, l_rectangle.TopLeft.Y)


                Else
                    ' l_rectangle.Rectangel.Stroke = New SolidColorBrush(p_color)
                End If

            Catch ex As Exception

            End Try
        Next



    End Sub





#End Region

    Private Sub m_UpdatesTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles m_UpdatesTimer.Elapsed

        Me.TextboxTime.Dispatcher.Invoke(New ItsTimeDel(AddressOf ItsTimeLabel))
        Me.timelineSlider.Dispatcher.Invoke(New ItsTimeDel(AddressOf ItsTimeSlider))
        Me.Dispatcher.Invoke(New ColorRectsDel(AddressOf ColorRectangles))
    End Sub

#Region "Xml Desirialize"

    Private Const MEDIA_FILES As String = "mediaFiles"
    Private Const MEDIA_FILE As String = "mediaFile"
    Private Const URL As String = "url"
    Private Const MEDIA_FILE_TYPE As String = "mediaFileType"
    Private Const ID As String = "id"
    Private Const GAME_INFO As String = "GameInfo"

    'Private Sub DownloadAllFiles(ByVal p_xGameInfo As XElement)
    '    Dim l_XmediaFiles As XElement = p_xGameInfo.Element(MEDIA_FILES)
    '    For Each l_mediaFileElement In l_XmediaFiles.Elements
    '        Dim l_url = l_mediaFileElement.Attribute(URL).Value
    '        Dim l_mediaFileType As MediaFileType = GetMediaFileTypeFromString(l_mediaFileElement.Attribute(MEDIA_FILE_TYPE).Value)
    '        Dim l_ID As Integer = l_mediaFileElement.Attribute(ID).Value
    '        Dim l_fileName = System.IO.Path.GetFileName(l_url)
    '        Dim l_Path = Path.Combine(Directory.GetParent(Directory.GetParent(Directory.GetParent(App_Path).ToString).ToString).ToString, Path.Combine("TempMovieFolder", l_fileName))
    '        'Dim l_Path = "C:\Users\Gal\Desktop\New Folder"


    '        Dim l_Success = DownloadFile(l_url, l_Path)
    '        If l_Success Then
    '            Dim l_mediafile As MediaFile

    '            If l_mediaFileType = MediaFileType.Movie Then
    '                l_mediafile = New Movie(l_ID, l_url, l_mediaFileType, l_Path)
    '            Else
    '                l_mediafile = New MediaFile(l_ID, l_url, l_mediaFileType, l_Path)
    '            End If
    '            m_GameInfo.MediaFiles.Add(l_mediafile)
    '        End If

    '    Next
    '    RaiseEvent DownladAllCompleted(p_xGameInfo)
    'End Sub

    Private Sub XmlDeserialize(ByVal p_path As String)
        Try
            Dim l_xdocument As XDocument = XDocument.Load(p_path)
            m_GameInfo = New GameInfo
            Dim l_xElementGameInfo As XElement = l_xdocument.FirstNode
            If l_xElementGameInfo.Name = GAME_INFO Then

                'Dim l_thread As New System.Threading.Thread(AddressOf Me.DownloadAllFiles)
                'l_thread.Start(l_xElementGameInfo)
                Dim l_element As XElement = l_xElementGameInfo.Element(MEDIA_FILES)
                For Each l_mediaFileElement In l_element.Elements
                    Dim l_url = l_mediaFileElement.Attribute(URL).Value
                    Dim l_mediaFileType As MediaFileType = GetMediaFileTypeFromString(l_mediaFileElement.Attribute(MEDIA_FILE_TYPE).Value)
                    Dim l_ID As Integer = l_mediaFileElement.Attribute(ID).Value
                    Dim l_fileName = System.IO.Path.GetFileName(l_url)
                    Dim l_Path = Path.Combine(GetTempFolderPath, l_fileName)
                    If Not Directory.Exists(Path.GetDirectoryName(l_Path)) Then
                        Directory.CreateDirectory(Path.GetDirectoryName(l_Path))
                    End If
                    'Dim l_Path = "C:\Users\Gal\Desktop\New Folder"


                    Dim l_Success = DownloadFile(l_url, l_Path)
                    If l_Success Then
                        Dim l_mediafile As MediaFile

                        If l_mediaFileType = MediaFileType.Movie Then
                            l_mediafile = New Movie(l_ID, l_url, l_mediaFileType, l_Path)
                        Else
                            l_mediafile = New MediaFile(l_ID, l_url, l_mediaFileType, l_Path)
                        End If
                        m_GameInfo.MediaFiles.Add(l_mediafile)
                    End If

                Next


                m_GameInfo.DesirializeFromXML(l_xElementGameInfo)

                ListViewMediaFiles.ItemsSource = New List(Of MediaFile)(m_GameInfo.MediaFiles)
                If ListViewMediaFiles.Items.Count > 0 Then
                    ListViewMediaFiles.SelectedItem = ListViewMediaFiles.Items(0)
                    For Each l_item In ListViewMediaFiles.Items
                        Dim l_media = (CType(l_item, MediaFile))
                        If l_media.ID = 1 Then
                            l_media.IsStartingMovie = True

                        End If
                    Next
                End If
                SetIDCounter()
            End If

        Catch ex As Exception
            MsgBox("Error : " & ex.ToString)
        End Try
    End Sub

    'Private Sub OnDownloadAllCompletedEvent(ByVal p_xElementGameInfo) Handles Me.DownladAllCompleted
    '    m_GameInfo.DesirializeFromXML(p_xElementGameInfo)
    '    ListViewMediaFiles.Dispatcher.Invoke(New ChangeMediaFilesItemsSourceDel(AddressOf ChangeMediaFilesItemsSource), m_GameInfo.MediaFiles, Nothing)

    'End Sub

    Private Sub SetIDCounter()
        Dim l_maxId As Integer = 0
        For Each l_media In m_GameInfo.MediaFiles
            If l_media.ID > l_maxId Then
                l_maxId = l_media.ID
            End If
            If l_media.Type = MediaFileType.Movie Then
                Dim l_movie = CType(l_media, Movie)
                For Each l_EOMResult In l_movie.EndOfMovieResults
                    If l_EOMResult.ResultID > l_maxId Then
                        l_maxId = l_EOMResult.ResultID
                    End If
                Next
                For Each l_event In l_movie.Events
                    If l_event.EventID > l_maxId Then
                        l_maxId = l_event.EventID

                    End If
                    For Each l_result In l_event.YesResultsList
                        If l_result.ResultID > l_maxId Then
                            l_maxId = l_result.ResultID
                        End If
                    Next
                    For Each l_result In l_event.NoResultsList
                        If l_result.ResultID > l_maxId Then
                            l_maxId = l_result.ResultID
                        End If
                    Next

                Next
            End If
        Next

        For Each l_Global In m_GameInfo.GlobalEvents
            If l_Global.EventID > l_maxId Then
                l_maxId = l_Global.EventID
            End If
        Next


        m_idCounter = l_maxId + 1

    End Sub


#End Region


#End Region

#Region "Properties"

    Public Property GameInfo() As GameInfo
        Get
            Return m_GameInfo
        End Get
        Set(ByVal value As GameInfo)
            m_GameInfo = value
            NotifyPropertyChanged("GameInfo")
        End Set
    End Property

    Public ReadOnly Property MediaFiles() As List(Of MediaFile)
        Get
            Return m_GameInfo.MediaFiles
        End Get
    End Property

    Public Property SelectedMediaFile() As MediaFile
        Get
            If ListViewMediaFiles.SelectedItem IsNot Nothing Then
                Return CType(ListViewMediaFiles.SelectedItem, MediaFile)
            Else
                Return Nothing
            End If
        End Get
        Set(ByVal value As MediaFile)

            NotifyPropertyChanged("SelectedMediaFile")
        End Set
    End Property

    Public ReadOnly Property GlobalEvents() As List(Of EventBase)
        Get
            Return GameInfo.GlobalEvents
        End Get

    End Property

    Public Property RubberBandProperty() As Shape
        Get
            Return rubberBand
        End Get
        Set(ByVal value As Shape)
            rubberBand = value
        End Set
    End Property


#End Region

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click

        Try

            Dim saveFileDialog1 As New SaveFileDialog()

            saveFileDialog1.Filter = "XML file (*.xml)|*.xml"
            saveFileDialog1.FilterIndex = 2
            saveFileDialog1.InitialDirectory = "C:\"
            saveFileDialog1.FileName = "Game.xml"
            saveFileDialog1.Title = "Select the Xml Path"

            If saveFileDialog1.ShowDialog() = Forms.DialogResult.OK Then
                Dim l_path = saveFileDialog1.FileName


                m_GameInfo.SerializeToXML(l_path)
            End If
        Catch ex As Exception

        End Try
       
    End Sub

  
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

        Try
            Dim l_openFileDialog As New OpenFileDialog
            l_openFileDialog.Filter = "XML file (*.xml)|*.xml"
            l_openFileDialog.InitialDirectory = "C:\"
            l_openFileDialog.Title = "Select the XML Path"
            If l_openFileDialog.ShowDialog = Forms.DialogResult.OK Then
                Dim l_path = l_openFileDialog.FileName
                XmlDeserialize(l_path)
            End If
        Catch ex As Exception

        End Try
    


    End Sub

  
    Private Sub buttonNew_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            If MessageBox.Show("Are you sure you want to leave the current game? unsaved changes will not be saved", "Confirmation", MessageBoxButtons.OKCancel) = Forms.DialogResult.OK Then
                m_GameInfo = New GameInfo
                ListViewMediaFiles.ItemsSource = New List(Of MediaFile)
                ListViewMovieEvents.ItemsSource = New List(Of EventBase)
                ListViewGlobalEvents.ItemsSource = New List(Of EventBase)
                ListViewResults.ItemsSource = New List(Of Result)
                If ListViewResults.Items.Count > 0 Then
                    ListViewResults.SelectedItem = ListViewResults.Items(0)
                Else : GridUsesrControls.Children.Clear()
                End If
            End If

        Catch ex As Exception

        End Try

      
    End Sub

    Public Delegate Sub DownladCompletedDelegate(ByVal p_MediaFileType As MediaFileType, ByVal p_url As String, ByVal p_path As String, ByVal p_Suceess As Boolean)
    Public Event DownloadCopleted As DownladCompletedDelegate

    Public Delegate Sub DownloadAllFilesComepletedDel(ByVal p_xGameInfo As XElement)
    Public Event DownladAllCompleted As DownloadAllFilesComepletedDel

    Private Sub ButtonManualTimeFrame_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim l_button = CType(sender, Windows.Controls.Button)
        Dim l_eventID = CType(l_button.Tag, Integer)
        Dim l_event As EventBase = Nothing
        If RBGlobalClickEvents.IsChecked Then
            l_event = (From l_Events In m_GameInfo.GlobalEvents Where l_Events.EventID = l_eventID Select l_Events).SingleOrDefault
        Else
            Dim l_movie As Movie = CType(ListViewMediaFiles.SelectedItem, Movie)
            l_event = (From l_ev In l_movie.Events Where l_ev.EventID = l_eventID Select l_ev).SingleOrDefault
        End If

        Dim l_manualTimeFrameDialog As New SetManulTimeFrame(l_event)
        l_manualTimeFrameDialog.Owner = Me
        If l_manualTimeFrameDialog.ShowDialog() Then
            l_event.TimeFrame = l_manualTimeFrameDialog.TimeFrame
        End If

    End Sub

   
End Class
